const express = require('express')
const router = express.Router()
const City = require('../db/model/CityModel')
const { mySend, Vtoken, checkParams } = require('../utils/index')
const { to } = require('await-to-js')

router.post('/searchById', async (req, res) => {
    const { id, token } = req.body
    let checked = checkParams({ id, token })
    if (checked) return mySend(res, 1, checked)
    let user = await Vtoken(token)
    if (!user) return mySend(res, 314, 'token不存在或已过期')
    let [err, result] = await to(City.findOne({ id }))
    if(err) return mySend(res, 1, '查询失败', err)
    return mySend(res, 0, 'success', result)
})

router.post('/searchByStr', async (req, res) => {
    const { str, token } = req.body
    let checked = checkParams({ str, token })
    if (checked) return mySend(res, 1, checked)
    let user = await Vtoken(token)
    if (!user) return mySend(res, 314, 'token不存在或已过期')
    const reg = new RegExp(str, 'i')
    let [err, result] = await to(City.find({ $or: [{ cityZh: reg }, { cityEn: reg }] }))
    if(err) return mySend(res, 1, '查询失败', err)
    return mySend(res, 0, 'success', result)
})

module.exports = router